#!/bin/bash
set -euo pipefail
#==============================================================#
# File      :   pg-badger
# Desc      :   Generate pgbadger HTML report to /pg/stat/logs
# Ctime     :   2021-09-17
# Mtime     :   2021-11-09
# Path      :   /pg/bin/pg-badger
# Deps      :   pgbadger, /pg/stat
# License   :   AGPLv3 @ https://doc.pgsty.com/about/license
# Copyright :   2018-2025  Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
PROG_NAME="$(basename $0)"
PROG_DIR="$(cd $(dirname $0) && pwd)"


#--------------------------------------------------------------#
#                             Usage                            #
#--------------------------------------------------------------#
# pg-badger       incremental report for today's log
# pg-badger full  full report for all historic log

# run as postgres
if [[ "$(whoami)" != "postgres" ]]; then
	echo "run this as dbsu postgres"
	exit 1
fi
mkdir -p /pg/stat/logs

MODE=${1-''}

LOGDIR=$(grep 'log_directory' /pg/data/postgresql.conf | awk '{print $3}' | tr -d "'")


#--------------------------------------------------------------#
#                             Main                             #
#--------------------------------------------------------------#
if [[ ${LOGDIR} == "full" ]]; then
	pgbadger \
	   -I ${LOGDIR}/*.csv \
	   -f csv \
	   --outdir /pg/stat/logs \
	   --wide-char \
	   --average 1 \
	   --sample 3
else
    LATEST_LOGS="$(find ${LOGDIR} -name '*.csv' -mtime 0)"
	pgbadger \
	   -I ${LATEST_LOGS} \
	   -f csv \
	   --outdir /pg/stat/logs \
	   --wide-char \
	   --average 1 \
	   --sample 3
fi